<template>
  <el-dialog
    width="600px"
    :visible.sync="isShow"
    :show-close="false"
    class="register"
  >
    <div class="title" slot="title">用户注册</div>

    <el-form :model="form" :rules="rules" label-width="90px" ref="form">
      <el-form-item label="头像" prop="avatar">
        <el-upload
          id="app"
          class="avatar-uploader upload-img"
          :action="baseURL + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="baseURL + '/' + form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item prop="username" label="名字">
        <el-input v-model="form.username"></el-input>
      </el-form-item>

      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>

      <el-form-item prop="phone" label="手机">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>

      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>

      <el-form-item prop="code" label="图形码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img
              :src="baseURL + codeUrl"
              alt
              class="code-img"
              @click="codeImgclick"
            />
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item prop="rcode" label="验证码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button @click="getCode" :disabled = 'totaiTime !=5'>获取验证码 <span v-if="totaiTime !=5">({{totaiTime}})</span></el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="submit">确定</el-button>
      <el-button @click="isShow = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {getPhoneCode , toRegister} from '@/api/register'
export default {
  data() {
    return {
      totaiTime:5,
      isShow: false,
      // imageUrl: "",
      baseURL: process.env.VUE_APP_URL,
      codeUrl: "/captcha?type=sendsms",
      form: {
        username: "", //	是	string	用户名
        phone: "", //	是	string	手机号
        email: "", //	是	string	邮箱
        avatar: "", //	是	string	头像地址
        password: "", //	是	string	密码
        code: "",
        rcode: "", //	是	string	验证码
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (value.length >= 2) {
                callback();
              } else {
                callback(new Error("用户名太短了"));
              }
            },
            trigger: "change",
          },
        ], //	是	string	用户名
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确手机号"));
              }
            },
            trigger: "change",
          },
        ], //	是	string	手机号
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确邮箱"));
              }
            },
            trigger: "change",
          },
        ], //	是	string	邮箱
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }], //	是	string	头像地址
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (value.length >= 6 && value.length <= 12) {
                callback();
              } else {
                callback(new Error("请输入6到12位密码"));
              }
            },
            trigger: "change",
          },
        ], //	是	string	密码
        code: [
          { required: true, message: "请输入图形码", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (value.length == 4) {
                callback();
              } else {
                callback(new Error("请输入4位图形码"));
              }
            },
            trigger: "change",
          },
        ],
        rcode: [
          { required: true, message: "请输入验证码", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (value.length == 4) {
                callback();
              } else {
                callback(new Error("请输入4位验证码"));
              }
            },
            trigger: "change",
          },
        ], //	是	string	验证码
      },
    };
  },
  watch:{
    isShow(newVal){
      if(!newVal){
        this.$refs.form.resetFields()
      }
    }
  },
  methods: {
    handleAvatarSuccess(res) {
      this.form.avatar = res.data.file_path;
      // this.imageUrl = res.data.file_path;

      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.$refs.form.validate((result) => {
        if (result) {

          toRegister(this.form).then(res =>{
              this.$message.success("成功");
              this.isShow = false
              console.log(res);
          })

          
        } else {
          this.$message.error("失败");
        }
      });
    },
    codeImgclick() {
      this.codeUrl = "/captcha?type=sendsms&jkmbk = " + Date.now();
    },
    getCode() {
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], (err) => {
        if (err == "") {
          num++;
        }
      });
      if (num == 2) {
          // this.$axios({
          //   url: "/sendsms",
          //   method: "post",
          //   data: {
          //     code: this.form.code,
          //     phone: this.form.phone,
          //   },

        this.totaiTime --
        let _interval = setInterval(()=>{
          this.totaiTime --
          if(this.totaiTime==0){
            this.totaiTime=5
            clearInterval(_interval)
          }
        },1000)


          getPhoneCode({
                code: this.form.code,
              phone: this.form.phone,
          })
          .then((res) => {
            this.$message.success(res.data.data.captcha + "");
          });
        } else {
          this.$message.error("请输入手机号和图形码");
        }
    },
  },
};
</script>

<style></style>
